package io.gitee.kotle.player.ui.view.exo

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.media3.common.MediaItem
import io.gitee.kotle.player.core.IPlayer
import io.gitee.kotle.player.core.impl.exoplayer.IExoPlayerMode

/**
 *  操作栏view
 */
open class ExoPlayerBarLayout : FrameLayout, IExoPlayerView {
    var isBottomBar = true

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    private var config: ExoPlayerViewConfig<IExoPlayerMode>? = null


    override fun onPlayerViewConfigCreated(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigCreated(player, config)
        config.singleTapConfirmed.observeForever(::singleTapConfirmed)
        this.config = config
    }


    override fun onPlayerViewConfigDestroyed(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigDestroyed(player, config)
        config.singleTapConfirmed.removeObserver(::singleTapConfirmed)
        this.config = null
    }


    private fun  singleTapConfirmed(show: Boolean?) {
        removeCallbacks(hideRun)
        if (show == true) {
            postDelayed(hideRun, 4000)
        }
        //这里一定b不为null，才可以执行下面的逻辑
        show ?: return
        if (show) {
            startAnim(0f)
        } else {
            if (height == 0) {
                post {
                    startAnim(height.toFloat())
                }
            } else {
                startAnim(height.toFloat())
            }
        }
    }

    private fun startAnim(finalY: Float) {
        if (finalY == translationY) {
            return
        }
        animate().cancel()
        animate().translationY(
            if (isBottomBar) {
                finalY
            } else {
                -finalY
            }
        )
            .setDuration(400)
            .start()
    }


    private val hideRun = Runnable {
        this.config?.singleTapConfirmed?.value = false
    }
}